package springcloudTest1.st1.uiT1.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import springcloudTest1.st1.uiT1.client.ComputeClient;
import springcloudTest1.st1.uiT1.client.dto.AddRequest;
import springcloudTest1.st1.uiT1.client.dto.AddResponse;

@RestController
public class ConsumerController {
    private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private ComputeClient computeClient;
	
	/**
	 * 使用resttemplate调用服务端
	 * @param a
	 * @param b
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public Integer add(@RequestParam Integer a,@RequestParam Integer b)
	{
		try{
			Integer result;
			result=this.restTemplate.getForEntity("http://st1-apiT1/add?a="+a+"&b="+b, Integer.class).getBody();
			logger.warn("客户端调用add");
			return result;
		}catch(Exception ex)
		{
			logger.error(ex.getMessage(),ex);
			return 0;
		}
	}
	
	/**
	 * 使用Feign调用服务端
	 * @param a
	 * @param b
	 * @return
	 */
	@RequestMapping(value="/addForFeign",method=RequestMethod.GET)
	public Integer addForFeign(@RequestParam Integer a,@RequestParam Integer b)
	{
		try{
			Integer result;
			result=this.computeClient.add(a, b);
			logger.warn("客户端使用feign调用add");
			return result;
		}catch(Exception ex)
		{
			logger.error(ex.getMessage(),ex);
			return 0;
		}
	}
	
	/**
	 * 使用resttemplate调用服务端(Post)
	 * @param a
	 * @param b
	 * @return
	 */
	@RequestMapping(value="/addByDto",method=RequestMethod.POST)
	public AddResponse addByDto(@RequestBody AddRequest req)
	{
		try{ 
			logger.warn("客户端调用add");
			//AddResponse res=this.restTemplate.getForEntity("http://st1-apiT1/addByDto", AddResponse.class,req).getBody();
			AddResponse res=this.restTemplate.postForEntity("http://st1-apiT1/addByDto", req, AddResponse.class).getBody();
			return res;
		}catch(Exception ex)
		{
			logger.error(ex.getMessage(),ex);
			AddResponse res=new AddResponse();
            res.setCode("500000");
            res.setMsg(ex.getMessage()); 
            return res;
		}
	}
}
